import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Layout,
  Typography,
  Button,
  Card,
  Progress,
  Row,
  Col,
  Avatar,
  Statistic,
  Tag,
  message,
  Alert
} from 'antd';
import {
  CloseOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  UploadOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { UploadManager, UploadTask } from '@/utils/uploadManager';
import { useServerConfig } from '@/contexts/ServerConfigContext';

const { Header, Content } = Layout;
const { Title, Text } = Typography;

interface UploadItem {
  id: string;
  fileName: string;
  progress: number;
  status: 'uploading' | 'completed' | 'failed';
  startTime: string;
  fileSize?: number;
  error?: string;
}

const ListenMode: React.FC = () => {

  const navigate = useNavigate();
  const { serverConfig } = useServerConfig();
  const [isActive, setIsActive] = useState(false);
  const [uploadItems, setUploadItems] = useState<UploadItem[]>([]);
  const [stats, setStats] = useState({
    totalUploaded: 0,
    currentlyUploading: 0,
    sessionDuration: '00:00:00'
  });
  const [config, setConfig] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);
  
  const uploadManagerRef = useRef<UploadManager | null>(null);
  const animationRef = useRef<number>();
  const startTimeRef = useRef<Date>(new Date());

  // 初始化配置并自动启动监听
  useEffect(() => {
    loadConfig();
  }, []);

  // 配置加载完成后自动启动监听
  useEffect(() => {
    if (config && config.apiKey && config.watchDirectory && !isActive) {
      startListening();
    }
  }, [config]);

  const loadConfig = async () => {
    try {
      let configData = null;

      // 优先使用electronAPI读取配置（生产环境）
      if (window.electronAPI && window.electronAPI.getConfig) {
        configData = await window.electronAPI.getConfig();
      } else {
        // 开发环境或备用方案：从localStorage读取
        const savedConfig = localStorage.getItem('picshare-config');
        if (savedConfig) {
          configData = JSON.parse(savedConfig);
        }
      }

      if (!configData) {
        throw new Error('未找到配置信息');
      }

      setConfig(configData);

      if (!configData.apiKey || !configData.watchDirectory) {
        setError('请先配置API密钥和监听目录');
        message.warning('请先在设置页面配置API密钥和监听目录');
      }
    } catch (err) {
      setError('加载配置失败: ' + (err instanceof Error ? err.message : String(err)));
      message.error('加载配置失败');
    }
  };

  // 启动监听（页面加载时自动调用）
  const startListening = async () => {
    if (!config?.apiKey || !config?.watchDirectory) {
      setError('请先配置API密钥和监听目录');
      return;
    }

    try {
      setError(null);
      
      // 创建上传管理器
      console.log('=== 创建 UploadManager ===');
      console.log('apiKey:', config.apiKey);
      console.log('serverConfig:', serverConfig);

      uploadManagerRef.current = new UploadManager({
        apiKey: config.apiKey,
        serverConfig: serverConfig, // 关键：传递服务器配置
        maxConcurrentUploads: 3,
        onTaskStart: (task: UploadTask) => {
          console.log('上传开始:', task.fileInfo.name);
          addUploadItem({
            id: task.id,
            fileName: task.fileInfo.name,
            progress: 0,
            status: 'uploading',
            startTime: new Date().toLocaleTimeString(),
            fileSize: task.fileInfo.size
          });
        },
        onTaskProgress: (task: UploadTask) => {
          updateUploadProgress(task.id, task.progress);
        },
        onTaskComplete: (task: UploadTask) => {
          console.log('上传完成:', task.fileInfo.name);
          updateUploadItem(task.id, {
            status: 'completed',
            progress: 100
          });
          setStats(prev => ({
            ...prev,
            totalUploaded: prev.totalUploaded + 1,
            currentlyUploading: Math.max(0, prev.currentlyUploading - 1)
          }));
          
          // 3秒后移除已完成的文件
          setTimeout(() => {
            setUploadItems(prev => prev.filter(item => item.id !== task.id));
          }, 3000);
        },
        onTaskError: (task: UploadTask) => {
          console.error('上传失败:', task.fileInfo.name, task.error);
          updateUploadItem(task.id, {
            status: 'failed',
            error: task.error
          });
          setStats(prev => ({
            ...prev,
            currentlyUploading: Math.max(0, prev.currentlyUploading - 1)
          }));
        }
      });

      // 启动主进程文件监听器
      console.log('=== 启动主进程文件监听器 ===');
      console.log('监听目录:', config.watchDirectory);

      if (window.electronAPI && window.electronAPI.startListening) {
        await window.electronAPI.startListening(config.watchDirectory);

        // 监听主进程发来的新文件通知
        window.electronAPI.onNewFileDetected((fileInfo) => {
          console.log('收到主进程新文件通知:', fileInfo.name);

          // 使用现有的上传管理器处理文件
          if (uploadManagerRef.current) {
            const taskId = uploadManagerRef.current.addUploadTask(fileInfo);
            console.log('添加到上传队列:', taskId);

            // 更新统计信息
            setStats(prev => ({
              ...prev,
              currentlyUploading: prev.currentlyUploading + 1
            }));
          }
        });
      } else {
        throw new Error('electronAPI 不可用，无法启动主进程监听');
      }
      setIsActive(true);
      startTimeRef.current = new Date();
      
    } catch (err) {
      setError('启动监听失败: ' + (err instanceof Error ? err.message : String(err)));
      message.error('启动监听失败');
    }
  };

  // 停止监听
  const stopListening = async () => {
    try {
      // 停止主进程监听
      if (window.electronAPI && window.electronAPI.stopListening) {
        await window.electronAPI.stopListening();
        // 移除新文件监听器
        window.electronAPI.removeNewFileListener();
      }

      // 清理上传管理器
      uploadManagerRef.current = null;
      setIsActive(false);
      message.info('监听模式已停止');
    } catch (error) {
      console.error('停止监听失败:', error);
      message.error('停止监听失败');
    }
  };

  // 更新会话时长
  useEffect(() => {
    if (!isActive) return;

    const updateDuration = () => {
      const now = new Date();
      const diff = now.getTime() - startTimeRef.current.getTime();
      const hours = Math.floor(diff / 3600000);
      const minutes = Math.floor((diff % 3600000) / 60000);
      const seconds = Math.floor((diff % 60000) / 1000);
      setStats(prev => ({
        ...prev,
        sessionDuration: `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
      }));
      animationRef.current = requestAnimationFrame(updateDuration);
    };

    animationRef.current = requestAnimationFrame(updateDuration);

    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
    };
  }, [isActive]);

  // 添加上传项目
  const addUploadItem = (item: UploadItem) => {
    setUploadItems(prev => [...prev, item]);
  };

  // 更新上传进度
  const updateUploadProgress = (id: string, progress: number) => {
    setUploadItems(prev => 
      prev.map(item => 
        item.id === id ? { ...item, progress } : item
      )
    );
  };

  // 更新上传项目状态
  const updateUploadItem = (id: string, updates: Partial<UploadItem>) => {
    setUploadItems(prev => 
      prev.map(item => 
        item.id === id ? { ...item, ...updates } : item
      )
    );
  };

  const handleExit = async () => {
    await stopListening();
    navigate('/dashboard');
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 截断过长的目录路径
  const truncateDirectory = (path: string, maxLength: number = 40): string => {
    if (path.length <= maxLength) return path;
    const parts = path.split('/');
    const filename = parts[parts.length - 1];
    const parent = parts[parts.length - 2];
    return `.../${parent}/${filename}`;
  };

  return (
    <Layout style={{ 
        height: '100vh', 
        background: 'linear-gradient(135deg, #0f0c29, #302b63, #24243e)',
        overflow: 'hidden'
      }}>
      <Header style={{ 
        background: 'rgba(0, 0, 0, 0.2)', 
        backdropFilter: 'blur(10px)',
        borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
        padding: '0 24px',
        height: '64px',
        display: 'flex',
        alignItems: 'center'
      }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          width: '100%'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <Avatar 
              size="large" 
              icon={<EyeOutlined />} 
              style={{ 
                background: isActive 
                  ? 'linear-gradient(45deg, #52c41a, #73d13d)' 
                  : 'linear-gradient(45deg, #8c8c8c, #bfbfbf)',
                boxShadow: isActive 
                  ? '0 0 20px rgba(82, 196, 26, 0.5)' 
                  : 'none'
              }}
            />
            <div>
              <Title level={4} style={{ color: '#fff', margin: 0, lineHeight: 1.2 }}>监听模式</Title>
            </div>
            {config?.watchDirectory && (
              <Text style={{ color: 'rgba(255, 255, 255, 0.8)', fontSize: '14px' }}>
                监听目录: {truncateDirectory(config.watchDirectory)}
              </Text>
            )}
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '24px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <Text style={{ color: 'rgba(255, 255, 255, 0.8)', fontSize: '14px', fontWeight: 'bold' }}>
                会话时长:
              </Text>
              <Text style={{ color: '#fff', fontSize: '16px', fontWeight: 'bold' }}>
                {stats.sessionDuration}
              </Text>
            </div>
            
            <Button
              type="primary"
              danger
              icon={<CloseOutlined />}
              onClick={handleExit}
              size="large"
              style={{
                background: 'rgba(255, 77, 79, 0.8)',
                border: 'none',
                borderRadius: '8px'
              }}
            >
              退出监听
            </Button>
          </div>
        </div>
      </Header>

      <Content style={{ 
        padding: '16px', 
        overflow: 'hidden',
        height: 'calc(100vh - 64px)'
      }}>
        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            closable
            onClose={() => setError(null)}
            style={{ marginBottom: '16px' }}
          />
        )}

        {/* 酷炫的监听动效区域 */}
        <div style={{ 
          position: 'relative', 
          height: '280px', 
          marginBottom: '16px',
          background: 'rgba(0, 0, 0, 0.2)',
          borderRadius: '16px',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          overflow: 'hidden'
        }}>
          {/* 中心眼镜 - 若隐若现效果 */}
          <div style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            fontSize: '64px',
            color: isActive ? '#52c41a' : '#8c8c8c',
            animation: isActive ? 'fadeInOut 3s ease-in-out infinite' : 'none',
            zIndex: 10
          }}>
            <EyeOutlined />
          </div>

          {/* 水波纹扩散效果 */}
          {isActive && [...Array(3)].map((_, index) => (
            <div key={index} style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '100px',
              height: '100px',
              borderRadius: '50%',
              border: '3px solid rgba(82, 196, 26, 0.8)',
              animation: `ripple ${4 + index * 0.8}s ease-out infinite`,
              animationDelay: `${index * 1.5}s`,
              zIndex: 5 - index
            }} />
          ))}

          {/* LISTENING 文字 - 呼吸闪烁效果 */}
          <div style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            marginTop: '120px',
            color: isActive ? 'rgba(255, 255, 255, 0.9)' : 'rgba(255, 255, 255, 0.3)',
            fontSize: '32px',
            fontWeight: 'bold',
            letterSpacing: '4px',
            animation: isActive ? 'breathing 2s ease-in-out infinite' : 'none',
            zIndex: 10
          }}>
            {isActive ? 'LISTENING' : 'STANDBY'}
          </div>
          
          {/* 状态指示器 */}
          <div style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            marginTop: '160px',
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            zIndex: 10
          }}>
            <div style={{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              background: isActive ? '#52c41a' : '#8c8c8c',
              animation: isActive ? 'blink 1.5s ease-in-out infinite' : 'none',
            }} />
            <Text style={{ color: 'rgba(255, 255, 255, 0.8)', fontSize: '14px' }}>
              {isActive ? '活跃监听中' : '监听已停止'}
            </Text>
          </div>

          {/* 内圈光晕 */}
          {isActive && (
            <div style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '150px',
              height: '150px',
              borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(82, 196, 26, 0.2) 0%, rgba(82, 196, 26, 0.05) 50%, transparent 70%)',
              animation: 'pulseGlow 4s ease-in-out infinite',
              zIndex: 3
            }} />
          )}
        </div>

        {/* 统计信息 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '16px' }}>
          <Col xs={8}>
            <Card style={{ 
              background: 'rgba(0, 0, 0, 0.2)', 
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              height: '80px'
            }} styles={{ 
              body: { 
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '16px',
                background: 'transparent',
                border: 'none'
              }
            }}>
              <Statistic
                title={<Text style={{ color: 'rgba(255, 255, 255, 0.7)', fontSize: '12px' }}>已上传</Text>}
                value={stats.totalUploaded}
                prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                valueStyle={{ color: '#fff', fontSize: '20px' }}
              />
            </Card>
          </Col>
          <Col xs={8}>
            <Card style={{ 
              background: 'rgba(0, 0, 0, 0.2)', 
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              height: '80px'
            }} styles={{ 
              body: { 
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '16px',
                background: 'transparent',
                border: 'none'
              }
            }}>
              <Statistic
                title={<Text style={{ color: 'rgba(255, 255, 255, 0.7)', fontSize: '12px' }}>上传中</Text>}
                value={stats.currentlyUploading}
                prefix={<UploadOutlined style={{ color: '#1890ff' }} />}
                valueStyle={{ color: '#fff', fontSize: '20px' }}
              />
            </Card>
          </Col>
          <Col xs={8}>
            <Card style={{ 
              background: 'rgba(0, 0, 0, 0.2)', 
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.1)',
              height: '80px'
            }} styles={{ 
              body: { 
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '16px',
                background: 'transparent',
                border: 'none'
              }
            }}>
              <Statistic
                title={<Text style={{ color: 'rgba(255, 255, 255, 0.7)', fontSize: '12px' }}>状态</Text>}
                value={isActive ? '活跃' : '停止'}
                prefix={<ClockCircleOutlined style={{ color: isActive ? '#52c41a' : '#8c8c8c' }} />}
                valueStyle={{ color: isActive ? '#52c41a' : '#8c8c8c', fontSize: '16px' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 当前上传进度 */}
        <Card style={{ 
          background: 'rgba(0, 0, 0, 0.2)', 
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          borderRadius: '16px',
          height: 'calc(100vh - 64px - 280px - 80px - 32px)'
        }} styles={{ 
          body: { 
            background: 'transparent',
            border: 'none',
            height: '100%',
            borderRadius: '16px'
          }
        }}>
          {!isActive ? (
            <div style={{ 
              display: 'flex', 
              flexDirection: 'column', 
              justifyContent: 'center', 
              alignItems: 'center',
              height: '100%',
              textAlign: 'center'
            }}>
              <EyeOutlined style={{ fontSize: '48px', color: 'rgba(255, 255, 255, 0.3)', marginBottom: '16px' }} />
              <Text type="secondary" style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '16px' }}>
                正在启动监听模式...
              </Text>
              {config?.watchDirectory && (
                <Text type="secondary" style={{ color: 'rgba(255, 255, 255, 0.3)', fontSize: '12px', marginTop: '8px' }}>
                  监听目录: {truncateDirectory(config.watchDirectory)}
                </Text>
              )}
            </div>
          ) : uploadItems.filter(item => item.status === 'uploading').length === 0 ? (
            <div style={{ 
              display: 'flex', 
              flexDirection: 'column', 
              justifyContent: 'center', 
              alignItems: 'center',
              height: '100%',
              textAlign: 'center'
            }}>
              <EyeOutlined style={{ fontSize: '48px', color: 'rgba(82, 196, 26, 0.3)', marginBottom: '16px' }} />
              <Text type="secondary" style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '16px' }}>
                监听中，等待新文件...
              </Text>
              <Text type="secondary" style={{ color: 'rgba(255, 255, 255, 0.3)', fontSize: '12px', marginTop: '8px' }}>
                已完成 {stats.totalUploaded} 个文件
              </Text>
            </div>
          ) : (
            uploadItems
              .filter(item => item.status === 'uploading')
              .slice(0, 1) // 只显示第一个正在上传的文件
              .map(item => (
                <div key={item.id} style={{ 
                  padding: '24px', 
                  background: 'rgba(255, 255, 255, 0.05)', 
                  borderRadius: '12px',
                  border: '1px solid rgba(255, 255, 255, 0.1)',
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center'
                }}>
                  <div style={{ textAlign: 'center', marginBottom: '24px' }}>
                    <Title level={4} style={{ color: '#fff', margin: 0, marginBottom: '8px' }}>
                      正在上传
                    </Title>
                    <Text style={{ color: 'rgba(255, 255, 255, 0.8)', fontSize: '16px' }}>
                      {item.fileName}
                    </Text>
                    {item.fileSize && (
                      <Text style={{ color: 'rgba(255, 255, 255, 0.5)', fontSize: '12px', marginLeft: '8px' }}>
                        ({formatFileSize(item.fileSize)})
                      </Text>
                    )}
                  </div>
                  
                  <Progress 
                    percent={Math.round(item.progress)} 
                    status="active"
                    strokeColor={{
                      '0%': '#667eea',
                      '100%': '#764ba2',
                    }}
                    strokeWidth={8}
                    style={{ marginBottom: '16px' }}
                  />
                  
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Text type="secondary" style={{ color: 'rgba(255, 255, 255, 0.7)' }}>
                      开始时间: {item.startTime}
                    </Text>
                    <Text style={{ color: '#fff', fontSize: '18px', fontWeight: 'bold' }}>
                      {Math.round(item.progress)}%
                    </Text>
                  </div>
                </div>
              ))
          )}
        </Card>
      </Content>

      <style>
        {`
          @keyframes fadeInOut {
            0%, 100% { opacity: 0.3; transform: translate(-50%, -50%) scale(0.8); }
            50% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
          }
          
          @keyframes ripple {
            0% { 
              width: 100px; 
              height: 100px; 
              opacity: 0.8; 
            }
            100% { 
              width: 800px; 
              height: 800px; 
              opacity: 0; 
            }
          }
          
          @keyframes breathing {
            0%, 100% { 
              opacity: 0.6; 
              transform: translate(-50%, -50%) scale(1);
            }
            50% { 
              opacity: 1; 
              transform: translate(-50%, -50%) scale(1.05);
            }
          }
          
          @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
          }
          
          @keyframes pulseGlow {
            0%, 100% { 
              opacity: 0.3; 
              transform: translate(-50%, -50%) scale(1);
            }
            50% { 
              opacity: 0.8; 
              transform: translate(-50%, -50%) scale(1.1);
            }
          }
        `}
      </style>
    </Layout>
  );
};

export default ListenMode;